package com.heima.wemedia.service.impl;


import com.heima.common.constants.user.UserRelationConstants;
import com.heima.feigns.BehaviorFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.PageRequestDTO;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.WmAttentionFansDto;
import com.heima.model.wemedia.dtos.WmReadCountByDateDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmFansListVo;
import com.heima.model.wemedia.vos.WmFansStatisticsVo;
import com.heima.model.wemedia.vos.WmFollowersPortraitVo;
import com.heima.utils.common.DateUtils;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserFansService;
import io.swagger.models.auth.In;
import jdk.nashorn.internal.ir.ReturnNode;
import org.apache.poi.ss.formula.WorkbookDependentFormula;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import sun.print.PeekGraphics;
import sun.text.resources.cldr.yo.FormatData_yo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lo
 * @date 2021/10/12
 */
@Service
public class WmUserFansServiceImpl implements WmUserFansService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    WmUserMapper wmUserMapper;

    @Autowired
    UserFeign userFeign;


    /**
     * 查询粉丝列表
     *
     * @param pageRequestDTO 分页参数
     * @return
     */
    @Override
    public ResponseResult getFansList(PageRequestDTO dto) {
        //1.校验参数
        dto.checkParam();

        //2.获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();

        //假数据向redis中添加数据

        // 查询当前登录的自媒体用户信息
        WmUser wmUser = wmUserMapper.getWmUser(userId);
        //3.从redis数据库中查询关注列表
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().reverseRangeWithScores(UserRelationConstants.FANS_LIST + userId, 0, -1);

        //获取到的是文章作者的id
        List<Integer> apUserIdList = new ArrayList<>();
        if (typedTuples.size() > 0) {
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                String apUserId = typedTuple.getValue();
                Integer integer = Integer.valueOf(apUserId);
                apUserIdList.add(integer);
            }
        }


        //是否关注
        Integer attention = 0;
        //添加用户数据
        ArrayList<WmFansListVo> wmFansListVos = new ArrayList<>();
        for (Integer integer : apUserIdList) {
            ResponseResult<ApUser> userById = userFeign.findUserById(integer);
            if (userById.checkCode() || userById.getData() != null) {

                ApUser data = userById.getData();
                WmFansListVo wmFansListVo = new WmFansListVo();
                wmFansListVo.setId(userId);
                wmFansListVo.setFans_name(data.getName());
                wmFansListVo.setFans_id(data.getId());
                //是指是否关注粉丝
                Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + integer, String.valueOf(userId));
                if (score != null) {
                    // 说明已经关注
                    attention = 1;
                } else {
                    attention = 0;
                }

                wmFansListVo.setIs_follow(attention);
                wmFansListVo.setPhoto(data.getImage());

                wmFansListVos.add(wmFansListVo);
            }

        }

        int size = wmFansListVos.size();

        //总记录数
        Long aLong = Long.valueOf(size);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), aLong, wmFansListVos);
        return result;
    }

    /**
     * 关注或取消关注粉丝
     *
     * @param pageRequestDTO
     * @return
     */
    @Override
    public ResponseResult attentionFans(WmAttentionFansDto dto) {
        //1.校验参数
        if (dto.getSwitchState() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Boolean switchState = dto.getSwitchState();

        //2.获取登录用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        //关注粉丝
        if (switchState) {
            //修改粉丝状态(给粉丝添加一条关注)
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST + dto.getFansId(), String.valueOf(userId), System.currentTimeMillis());
            return ResponseResult.okResult();
        }
        //取消关注
        // ResponseResult result = userFeign.changeState(dto.getFansId(), switchState);
        redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + dto.getFansId(), String.valueOf(userId));
        return ResponseResult.okResult();
    }


    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 粉丝画像功能
     *
     * @return
     */
    @Override
    public ResponseResult fansPortrayal() {
        //1.获取当前登录用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();

        //2.根据用户id来获取redis的粉丝apuserid列表
        ArrayList<Integer> list = new ArrayList<>();
        Set<String> range = redisTemplate.opsForZSet().range(UserRelationConstants.FANS_LIST + userId, 0, -1);
        for (String apUserId : range) {
            Integer id = Integer.valueOf(apUserId);
            //放入list集合
            list.add(id);
        }
        //封装所有粉丝数据
        ArrayList<WmFollowersPortraitVo> wmFoList = new ArrayList<>();
        //获取所有粉丝数据
        ArrayList<ApUser> apUserArrayList = new ArrayList<>();

        //3.远程调用获取apUser
        for (Integer id : list) {
            ResponseResult<ApUser> userById = userFeign.findUserById(id);
            if (userById.checkCode() || userById.getData() != null) {
                ApUser data = userById.getData();
                apUserArrayList.add(data);

                WmFollowersPortraitVo wmFollowersPortraitVo = new WmFollowersPortraitVo();
                wmFollowersPortraitVo.setId(data.getId());
                wmFollowersPortraitVo.setUserId(userId);
                if (data.getSex()) {
                    //男
                    wmFollowersPortraitVo.setName("sex:male");
                } else {
                    //女
                    wmFollowersPortraitVo.setName("sex:female");
                }
                wmFollowersPortraitVo.setValue("1");
                wmFoList.add(wmFollowersPortraitVo);
            }
        }
        Integer maleNum = 0;
        Integer femaleNum = 0;
        for (WmFollowersPortraitVo portraitVo : wmFoList) {
            if ("sex:male".equals(portraitVo.getName())) {
                maleNum++;
            } else {
                femaleNum++;
            }
        }
        //返还给前端的集合
        ArrayList<WmFollowersPortraitVo> followersPortraitVos = new ArrayList<>();
        /**
         * 男
         */
        WmFollowersPortraitVo maleWm = new WmFollowersPortraitVo();
        maleWm.setId(1);
        maleWm.setUserId(userId);
        maleWm.setName("sex:male");
        maleWm.setValue("6");
        // maleWm.setValue(maleNum.toString());
        maleWm.setCreatedTime(new Date());
        followersPortraitVos.add(maleWm);

        /**
         * 女
         */
        WmFollowersPortraitVo femaleWm = new WmFollowersPortraitVo();
        femaleWm.setId(1);
        femaleWm.setUserId(userId);
        femaleWm.setName("sex:female");
        femaleWm.setValue(femaleNum.toString());
        femaleWm.setCreatedTime(new Date());
        followersPortraitVos.add(femaleWm);

        /**
         * 苹果: 假数据
         * mobile:ios
         */
        WmFollowersPortraitVo iosWm = new WmFollowersPortraitVo();
        iosWm.setId(1);
        iosWm.setUserId(userId);
        iosWm.setName("mobile:ios");
        iosWm.setValue("30");
        iosWm.setCreatedTime(new Date());
        followersPortraitVos.add(iosWm);

        /**
         * 安卓: 假数据
         *mobile:andorid
         */
        WmFollowersPortraitVo andoridWm = new WmFollowersPortraitVo();
        andoridWm.setId(1);
        andoridWm.setUserId(userId);
        andoridWm.setName("mobile:android");
        andoridWm.setValue("20");
        andoridWm.setCreatedTime(new Date());
        followersPortraitVos.add(andoridWm);


        /**
         * 年龄
         * 10 -20
         */
        List<ApUser> oneApUser = apUserArrayList.stream().filter(apUser -> {
            if (apUser.getAge() >= 0 && apUser.getAge() <= 20) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        WmFollowersPortraitVo oneWm = new WmFollowersPortraitVo();
        oneWm.setId(2);
        oneWm.setUserId(userId);
        oneWm.setName("age:0-20");
        int size = oneApUser.size();

        oneWm.setValue(String.valueOf(size));
        oneWm.setCreatedTime(new Date());
        followersPortraitVos.add(oneWm);


        /**
         * 20-30
         */
        List<ApUser> twoApUser = oneApUser.stream().filter(apUser -> {
            if (apUser.getAge() >= 20 && apUser.getAge() <= 30) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        WmFollowersPortraitVo twoWm = new WmFollowersPortraitVo();
        twoWm.setId(2);
        twoWm.setUserId(userId);
        twoWm.setName("age:20-30");
        int oneSize = oneApUser.size();

        // twoWm.setValue(String.valueOf(oneSize));
        twoWm.setValue(String.valueOf(20));

        twoWm.setCreatedTime(new Date());
        followersPortraitVos.add(twoWm);

        /**
         * 获取过去一个星期的每天的所有文章的阅读量
         */

        for (int i = -6; i < 1; i++) {
            Date sDate = DateUtils.addDay(new Date(), i);
            String stime = DateUtils.dateToString(sDate, DateUtils.MY_DATE_TIME_FORMAT);

            Date eDate = DateUtils.addDay(new Date(), i + 1);
            String etime = DateUtils.dateToString(eDate, DateUtils.MY_DATE_TIME_FORMAT);


            ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(userId, null);
            if (!result.checkCode() || result.getData() == null) {
                ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            ApBehaviorEntry entry = result.getData();
            String entryId = entry.getId();
            List<ApReadBehavior> apReadBehaviorList = mongoTemplate.find(Query.query(Criteria
                            .where("entryId").is(entryId)),
                    ApReadBehavior.class);

            List<ApReadBehavior> currentList = apReadBehaviorList.stream().filter(read -> {
                Date createdTime = read.getCreatedTime();
                String dateToString = DateUtils.dateToString(createdTime, DateUtils.MY_DATE_TIME_FORMAT);
                if (stime.equals(dateToString)) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());

            Integer allCount = 0;
            for (ApReadBehavior behavior : currentList) {
                Short count = behavior.getCount();
                allCount += count;
            }

            Integer s = (i + 10) * 2;

            WmFollowersPortraitVo dateWm = new WmFollowersPortraitVo();
            dateWm.setId(4);
            dateWm.setUserId(userId);
            dateWm.setName("read:" + stime);
            // dateWm.setValue(allCount.toString());
            dateWm.setValue(String.valueOf(s));
            dateWm.setCreatedTime(new Date());
            followersPortraitVos.add(dateWm);

        }

        return ResponseResult.okResult(followersPortraitVos);
    }
}
